// TODO: CODE REVIEW & CLEANUP!
//
// MusicLibraryScreen.xaml.cs
//

using System;
using System.Windows;
using System.Windows.Controls;
using System.Xml;
using HomeUX.ClientAppSupport;
using HomeUX.ClientControlSupport;
using HomeUX.Controls;
using HomeUX.Synchronization;
using HomeUX.Utilities;

namespace HomeUX.MusicClientLibrary
{

public partial class MusicLibraryScreen : UserControl
{
    MusicClientHelper _musicClientHelper;
    Style _artistTextStyle;

    /// <summary>
    /// A <n>String.Format</n>-style format string to use for <n>HeaderTextBlock</n>.  Initialized
    /// from the design-time text value of  <n>HeaderTextBlock</n>.
    /// </summary>
    string _headerFormatString;

    public MusicLibraryScreen()
    {
        InitializeComponent();

        // initialize <_headerFormatString>
        _headerFormatString = HeaderTextBlock.Text;

        // hook up events
        Loaded += MusicLibraryScreen_Loaded;
        GotFocus += MusicLibraryScreen_GotFocus;
    }

    void MusicLibraryScreen_Loaded(object sender, RoutedEventArgs e)
    {
        _musicClientHelper = new MusicClientHelper(this, BeginLoadingDataFromMusicServer,
            OnParcelReceived);

        // reset screen state if we disconnect, or connect to a different server
        _musicClientHelper.Screen.Reset += delegate
        {
            ArtistsListBox.Items.Clear();
            _musicClientHelper.TryToLoadData(); // reload library when we reconnect
        };

        HeaderTextBlock.Text = String.Format(_headerFormatString, _musicClientHelper.MusicDeviceName);

        _artistTextStyle = (Style)LayoutRoot.Resources["ArtistTextStyle"];

        // if the music server is already available, request the list of artists now; otherwise,
        // wait until it's available
        _musicClientHelper.TryToLoadData();
    }

    void BeginLoadingDataFromMusicServer()
    {
        ArtistsListBox.Items.Clear();
        string command = ParsedSyncNodeCommand.Format("GetArtists",
             "RecipientId", XmlConvert.ToString(_musicClientHelper.RecipientId));
        _musicClientHelper.MusicDeviceNode.ExecuteCommand(command);
    }

    void OnParcelReceived(Guid recipientId, XmlReader reader)
    {
        try
        {
            foreach (XmlElementInfo element in XmlElementInfo.EnumerateElements(reader))
            {
                switch (element.Name)
                {

                case "Artist":

                    AddArtistToList(element.GetRequiredAttribute("Name"),
                        element.GetRequiredAttribute("SortKey"));
                    break;

                case "/Artists":

                    _musicClientHelper.OnDataLoaded();
                    break;

                }
            }
        }
        catch (InvalidOperationException ex)
        {
            ClientGlobals.Alert(AlertType.Warning,
                "Invalid reply from server: {0}", ex.Message);
        }
    }


    //void EnableOrDisableScreen()
    //{
    //    /*
    //    IsEnabled = (_musicServerNode.Value != null);

    //    if (IsEnabled)
    //        HideNotAvailableMessage();
    //    else
    //        ShowNotAvailableMessage();
    //    */
    //    _screen.ShowModalMessageBox((_musicServerNode.Value != null) ? null :
    //        "The music server is not available");
    //}

    /*
    void UpdateModalMessage()
    {
        if (_musicServerNode.Value == null)
            _screen.ShowModalMessageBox("The music server is not available");
        else
        if (_isLoading)
            _screen.ShowModalMessageBox("Loading...");
        else
            _screen.CloseModalMessageBox();
    }
    */

    //void _musicServerNode_ValueChanged(object sender, ValueChangedEventArgs e)
    //{
    //    UpdateModalMessage();
    //    TryRequestingArtists();
    //}

    //void _libraryChangeCountNode_ValueChanged(object sender, ValueChangedEventArgs e)
    //{
    //    // this method is called when the contents of the music library may have changed
    //    TryRequestingArtists();
    //}

    /*
    /// <summary>
    /// Asks the server for a list of music server artists.  When this request is complete,
    /// <r>OnRequestArtistsReplyReceived</r> is called.  This method does nothing if the music
    /// server is not available, or if we already have an up-to-date list of artists.
    /// </summary>
    void TryRequestingArtists()
    {
        if ((_musicServerNode.Value != null) &&
            (_libraryChangeCountNode.Value != null) &&
            (_libraryChangeCount != (int)_libraryChangeCountNode.Value))
        {
            _libraryChangeCount = (int)_libraryChangeCountNode.Value;
            _isLoading = true;
            UpdateModalMessage();
            //LoadingTextBlock.Visibility = Visibility.Visible;
            _musicServerNode.ExecuteCommand(
                ParsedSyncNodeCommand.Format("GetArtists",
                "RecipientId", XmlConvert.ToString(_recipientId)));
            ArtistsListBox.Items.Clear();
        }
    }
    */

    /// <summary>
    /// Called when the request begun by <r>RequestArtists</r> has completed.  This method is
    /// called once for each artist.
    /// </summary>
    void AddArtistToList(string name, string sortKey)
    {
        var textBlock = new TextBlock()
        {
            Text = name,
            Tag = name,
            Style = _artistTextStyle
        };
        TouchSelector.SetIndexLetter(textBlock,
            ((sortKey.Length > 0) ? sortKey[0] : ' '));
        ArtistsListBox.Items.Add(textBlock);
    }

    //void ShowNotAvailableMessage()
    //{
    //    if (_noMusicServerMessageBox == null)
    //    {
    //        _noMusicServerMessageBox = TouchMessageBox.Show(this,
    //            "The music server is not available", null,
    //            delegate
    //            {
    //                _noMusicServerMessageBox = null;
    //            });
    //    }
    //}

    //void HideNotAvailableMessage()
    //{
    //    if (_noMusicServerMessageBox != null)
    //    {
    //        ControlHelper.CloseDialog(_noMusicServerMessageBox, false);
    //        _noMusicServerMessageBox = null;
    //    }
    //}

    void MusicLibraryScreen_GotFocus(object sender, RoutedEventArgs e)
    {
        ArtistsListBox.Focus();
    }

    private void ArtistsListBox_ItemClick(object sender, ItemClickEventArgs e)
    {
        string artistName = (string) e.ItemValue;

        Screen screen;
        MusicArtistScreen screenControl;
        _musicClientHelper.FindMusicScreen("Artist", out screen, out screenControl);
        screenControl.ArtistName = artistName;
        screen.GoTo();
    }
}

}
